
#' @title sampling excacuter
#' @param sampleMethod an sample method object. it can be 'eToe', 'pToe', 
#'        'tSquare','pSquare'
#' @param populationData an population object
#' @param visul if it is true, the samples will be ploted on the population plot.

#
# 注意点不能重复！！！
#define sampling method for all object
sampling=function(sampleMethod,populationData,visul=F,quick=F){
	j=1
	#先规定内缘可取的区域
	populationData=borderEdgeCorrection(populationData,sampleMethod@edge)
	#if quick is true, then use the qick method
	if(quick){
		re=samplingQuick(sampleMethod,populationData)
		attr(re,"plotdim")=populationData@plotdim
		attr(re,"sampleMethod")=sampleMethod
		return(re)	
	}
	while(j<=sampleMethod@time){
		#随机在可取区域内选择一点或多点
		availible=oneSampling(sampleMethod,populationData)
		if(!is.null(attr(availible,"distanceOBJ")))
		   sampleMethod=attr(availible,"distanceOBJ")
		i=1
		j=j+1
	
		#检查是否有非重叠要求
	if(!sampleMethod@overlap){
		#判断这次取的点与之前取的点是否有重复
			#由于基于距离的和基于样方的判断重复逻辑不同，因此分两种情况对待、
		if(is(sampleMethod,"distance")){
			while(length(populationData@sampled)!= 1 & any(populationData@sampled[availible]) & i <= sampleMethod@stopLimit){
				#如果有，则尝试再次取样，直到取到不重复点或着是达到最大取样次数限制
				availible=oneSampling(sampleMethod,populationData)
				i=i+1
			}
		}else if(is(sampleMethod,"quadrat")){
			while(isAreaOverlaped(availible,populationData,sampleMethod)){
				availible=oneSampling(sampleMethod,populationData)
				i=i+1
			}
		}
		
	}
	
	#如果取样成功，则设置取样结果
	if(!isReachLimit(i,sampleMethod)@success){
		if(is(sampleMethod,"distance")){
			populationData=setSampledPoints(availible,populationData)
		}else if(is(sampleMethod,"quadrat")){
			populationData=setSampleArea(availible,populationData)
		}
		
		populationData=setSampleResult(sampleMethod,availible,populationData)
	}
	}
	#如果需要画出取样图，则进行画图
	if(visul){
   		plot(sampleMethod,populationData)
	}
	attr(populationData,"sampleMethod")=sampleMethod
	#最后返回包含了取样数据的种群对象
	return(populationData)
}

#定义一个多核快速计算函数，并忽略错误信息
sampling.multicore=function(sampleMethod,population){
	re=try(sampling(sampleMethod,population,quick=T))
	if(class(re)=="try-error"){
		re=NA
	}
	return(re)
}

